<?php

namespace origin;

use origin\Exception;

/**
 * Redis类
 * @explain 获取Redis实例
 * @author  dece <decezz@qq.com>
 */
class Redis
{

    private function __construct() {}

    /**
     * 连接redis
     * @param  array    $redisConf  redis配置
     * @return object   $redis      redis实例
     */
    public static function connect ( $redisConf = array() )
    {
        if (!class_exists('Redis')) {
            throw new Exception("Not find Redis class", 501);
        }

        // 合并配置
        $redisConf = array_merge([
            'host'  => '127.0.0.1',
            'port'  => '6379',
            'pass'  => '',
        ], $redisConf);

        $redis = new \Redis();

        // 尝试连接
        if (!$redis->connect($redisConf['host'], $redisConf['port'])) {
            throw new Exception("Redis connect error", 502);
        }

        // 验证密码
        if (!empty($redisConf['pass']) && !$redis->auth($redisConf['pass'])) {
            throw new Exception("Redis password error", 503);
        }

        return $redis;
    }
    
    /**
     * 未知方法名连接redis
     * @param  string   $method     方法名
     * @param  array    $params     redis配置
     * @return object   $redis      redis实例
     */
    public static function __callStatic ( $method , $params )
    {
        return call_user_func_array(['self', 'connect'], $params);
    }

}